package com.usf.jprovider.schema.provider.file.formated;

import java.io.IOException;

import javax.xml.bind.annotation.XmlAttribute;

import com.usf.jprovider.constants.Constants;
import com.usf.jprovider.object.JObjectNode;
import com.usf.jprovider.object.env.Environment;
import com.usf.jprovider.object.type.JType;
import com.usf.jprovider.tools.CSVTools;

public final class CSVFile extends AbstractFormatedFileSource {
	
	@XmlAttribute protected int columnIndex;
	@XmlAttribute protected int rowStart;
	@XmlAttribute protected String colsSeparator;
	
	public CSVFile() {
		super();
		colsSeparator = Constants.CSV_DEFAULT_FILE_SEPARATOR;
		rowStart = Constants.CSV_DEFAULT_ROW_START_INDEX;
		columnIndex = Constants.CSV_DEFAULT_COLUMN_INDEX;
	}
	public String getColsSeparator() {
		return colsSeparator;
	}
	public int getColumnIndex() {
		return columnIndex;
	}
	public int getRowStart() {
		return rowStart;
	}
	
	@Override
	protected String createUnformated(Environment env, JObjectNode node) throws Exception {
		String[] column = (String[])cacheValues(env, node);
		String value = entrySelector.create(env, node, column);
		return valueSelector.create(env, node, value);
	}
	@Override
	public boolean checkValue(Environment env, JObjectNode node, JType<?> object)  throws Exception {
		String value = object.toString();
		String[] column = (String[])cacheValues(env, node);
		int index = entrySelector.check(env, node, column, value);
		return valueSelector.check(env, node, column[index], value);
	}
	@Override
	public Object values(Environment env) throws IOException {
		return CSVTools.columnValues(env.fullPath(path), columnIndex, colsSeparator, rowStart).split(colsSeparator);
	}
	@Override
	protected String cacheIdentifier(){
		return "col_" + columnIndex + "-" + path;
	}	
}
